<template>
	<div class="httpView">
		<shyt-table
			ref="shytTable"
			:columns="columns"
			:data="tableData"
			:auto-resize="true"
			:keep-source="true"
			:toolbar-config="toolbarConfig"
			:edit-config="{ trigger: 'dblclick', mode: 'row', showStatus: true }"
		>
			<template #toolbar_buttons>
				<el-input
					v-model="query"
					placeholder="请输入"
					size="small"
					style="width: 200px"
					clearable
					@keyup.enter.native="handlerSearch"
				>
					<el-button
						slot="append"
						icon="el-icon-search"
						@click="handlerSearch"
					/>
				</el-input>
				<el-button type="primary" size="small" @click="handlerAddClick">
					新增
				</el-button>
				<el-button type="danger" size="small" @click="handlerDelSelect">
					删除
				</el-button>
				<el-button type="success" size="small" @click="handlerSave">
					保存
				</el-button>
				<el-button size="small" @click="$table.revertData()"> 重置 </el-button>
			</template>
			<template #edit="{ row }">
				<el-button type="text" size="small" @click="handlerEditRow(row)">
					编辑
				</el-button>
				<el-button type="text" size="small" @click="handlerDelRow(row)">
					删除
				</el-button>
			</template>
		</shyt-table>
	</div>
</template>

<script>
import {
	getCacheUrl,
	setCacheUrl,
	removeCacheUrl,
	iterateCacheUrl,
	clearCacheUrl,
} from '@/http/useCache'
// import { nanoid } from 'nanoid'
export default {
	name: 'AjaxCache',
	data() {
		return {
			tableData: [],
			oldTableData: [],
			query: '',
			columns: [
				{ type: 'checkbox', width: 50 },
				{
					title: '缓存接口地址',
					field: 'cacheUrl',
					editRender: { name: 'ElInput' },
				},
				{
					title: '操作',
					width: '100',
					slots: { default: 'edit' },
				},
			],
			$table: null,
			toolbarConfig: {
				slots: {
					buttons: 'toolbar_buttons',
				},
			},
		}
	},
	async mounted() {
		this.$table = this.$refs.shytTable.$refs.xTable
		// this.$http.get('/static/1.json').then(res => {
		// 	console.log('请求结果：', res)
		// })
		// this.checkInser(this.tableData)
		const res = [{ cacheUrl: '/abc' }]
		const urlList = await iterateCacheUrl()
		this.tableData = this._.uniqBy([...res, ...urlList], 'cacheUrl')
		this.tableDataCopy = Object.freeze(
			this._.uniqBy([...res, ...urlList], 'cacheUrl'),
		)
		this.oldTableData = this._.uniqBy([...res, ...urlList], 'cacheUrl')
		await clearCacheUrl()
		this.tableData.forEach(async item => {
			const res = await getCacheUrl(item.cacheUrl)
			if (!res) {
				setCacheUrl(item.cacheUrl, true)
			}
		})
	},
	methods: {
		handlerSearch() {
			if (this.query !== '') {
				this.tableData = this.tableDataCopy.filter(i => {
					return i.cacheUrl.includes(this.query)
				})
			} else {
				this.tableData = this._.cloneDeep(this.tableDataCopy)
			}
		},
		handlerUpdateTableData() {
			this.oldTableData = this._.cloneDeep(this.tableData)
			this.$table.reloadData(this.tableData)
		},
		handlerDelSelect() {
			this.$table.removeCheckboxRow()
		},
		checkInser(arr) {
			if (!arr.length) return
			const rptArr = []
			arr.forEach(async item => {
				const url = this.tableData.find(i => {
					return i.cacheUrl === item.cacheUrl
				})
				if (url) {
					rptArr.push(item.cacheUrl)
				} else {
					this.tableData.push(item)
					if (!(await getCacheUrl(item.cacheUrl))) {
						setCacheUrl(item.cacheUrl, true)
					}
				}
			})
			if (rptArr.length > 0) {
				this.$notify({
					title: '警告:以下地址已存在',
					message: rptArr.join(','),
					type: 'warning',
				})
			}
			this.handlerUpdateTableData()
		},
		checkRemove(arr) {
			if (!arr.length) return
			arr.forEach((i, index) => {
				removeCacheUrl(i.cacheUrl)
				this.tableData.splice(index, 1)
			})
			this.handlerUpdateTableData()
		},
		checkUpdate(arr) {
			if (!arr.length) return
			arr.forEach(i => {
				const res = this.oldTableData.find(j => j.cacheUrl === i.cacheUrl)
				removeCacheUrl(res.cacheUrl).then(() => {
					setCacheUrl(i.cacheUrl, true)
					this.handlerUpdateTableData()
				})
			})
		},
		handlerSave() {
			const { insertRecords, removeRecords, updateRecords } =
				this.$table.getRecordset()
			if (
				!insertRecords.length &&
				!removeRecords.length &&
				!updateRecords.length
			) {
				this.$message.warning('数据无变化')
			} else {
				this.checkInser([...insertRecords])
				this.checkRemove([...removeRecords])
				this.checkUpdate([...updateRecords])
			}
		},
		handlerEditRow(row) {
			// console.log(row)
			this.$table.setActiveRow(row)
		},
		handlerDelRow(row) {
			this.$table.remove(row)
		},
		handlerAddClick() {
			this.$table.insert({ cacheUrl: '' })
		},
	},
}
</script>

<style lang="scss" scoped>
.httpView {
	padding: 10px;
	box-sizing: border-box;
}
</style>
